package com.chutoutian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chutoutian.mapper.AddressMapper;
import com.chutoutian.po.Address;
import com.chutoutian.service.AddressService;
import com.chutoutian.untils.SnowflakeIdWorker;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    @Override
    public void add(Address address) {
        address.setId(SnowflakeIdWorker.getId());
        if ("1".equals(address.getIsDefault())) {
            Address param = new Address();
            param.setIsDefault("0");
            QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", address.getUserId());
            addressMapper.update(param, queryWrapper);
        }
        addressMapper.insert(address);
    }

    @Override
    public Address get(String id) {
        return addressMapper.selectById(id);
    }

    @Override
    public void update(Address address) {
        if ("1".equals(address.getIsDefault())) {
            Address param = new Address();
            param.setIsDefault("0");
            QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", address.getUserId());
            addressMapper.update(param, queryWrapper);
        }
        addressMapper.updateById(address);
    }

    @Override
    public void delete(String id) {
        addressMapper.deleteById(id);
    }

    @Override
    public List<Address> find(Address address) {
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>(address);
        return addressMapper.selectList(queryWrapper);
    }


}
